#include "adaptivefilelayout.h"
#include <QWidget>
#include <QDebug>
#include <QtMath>
#include <QWidgetItem>
#include <QApplication>
#include <QEasingCurve>

using namespace SonyIveDesign;

AdaptiveFileLayout::AdaptiveFileLayout(QWidget* parent)
    : QLayout(parent)
    , m_engine(nullptr)
    , m_columns(1)
    , m_spacing(DesignConstants::SPACING_NORMAL)
    , m_margins(DesignConstants::SPACING_NORMAL, DesignConstants::SPACING_NORMAL,
               DesignConstants::SPACING_NORMAL, DesignConstants::SPACING_NORMAL)
    , m_animationEnabled(true)
    , m_animationDuration(DesignConstants::ANIMATION_DURATION_NORMAL)
    , m_activeAnimations(0)
    , m_performanceMode(false)
    , m_throttleInterval(50)
    , m_layoutInvalid(true)
    , m_currentDisplayMode(DisplayMode::Standard)
    , m_isUpdating(false)
{
    setContentsMargins(m_margins);

    // 初始化动画系统
    m_animationGroup = new QParallelAnimationGroup(this);
    connect(m_animationGroup, &QParallelAnimationGroup::finished,
            this, &AdaptiveFileLayout::onAnimationFinished);

    // 初始化更新计时器
    m_updateTimer = new QTimer(this);
    m_updateTimer->setSingleShot(true);
    m_updateTimer->setInterval(m_throttleInterval);
    connect(m_updateTimer, &QTimer::timeout,
            this, &AdaptiveFileLayout::onThrottledUpdate);

}

AdaptiveFileLayout::~AdaptiveFileLayout()
{
    stopAllAnimations();

    // 清理布局项
    for (auto& info : m_items) {
        if (info.animation) {
            info.animation->deleteLater();
        }
        delete info.item;
    }
    m_items.clear();

}

// === QLayout接口实现 ===

void AdaptiveFileLayout::addItem(QLayoutItem* item)
{
    if (!item) return;

    LayoutItemInfo info(item);
    m_items.append(info);
    m_cache.invalidate();
    invalidateLayout();

}

QLayoutItem* AdaptiveFileLayout::itemAt(int index) const
{
    if (index >= 0 && index < m_items.size()) {
        return m_items.at(index).item;
    }
    return nullptr;
}

QLayoutItem* AdaptiveFileLayout::takeAt(int index)
{
    if (index < 0 || index >= m_items.size()) {
        return nullptr;
    }

    LayoutItemInfo info = m_items.takeAt(index);
    if (info.animation) {
        info.animation->stop();
        info.animation->deleteLater();
    }

    m_cache.invalidate();
    invalidateLayout();

    return info.item;
}

int AdaptiveFileLayout::count() const
{
    return m_items.size();
}

QSize AdaptiveFileLayout::sizeHint() const
{
    if (m_items.isEmpty()) {
        QSize itemSize = m_engine ? m_engine->calculateItemSize(m_currentDisplayMode) : QSize(280, 48);
        return QSize(itemSize.width(), itemSize.height()) + QSize(m_margins.left() + m_margins.right(),
                                                                    m_margins.top() + m_margins.bottom());
    }

    // 基于当前显示模式和列数计算理想大小
    QSize itemSize = m_engine ? m_engine->calculateItemSize(m_currentDisplayMode) : QSize(280, 48);
    int rows = calculateRowCount();

    int width = m_columns * itemSize.width() + (m_columns - 1) * m_spacing;
    int height = rows * itemSize.height() + (rows - 1) * getAdaptiveSpacing(m_currentDisplayMode);

    width += m_margins.left() + m_margins.right();
    height += m_margins.top() + m_margins.bottom();

    return QSize(width, height);
}

QSize AdaptiveFileLayout::minimumSize() const
{
    if (m_items.isEmpty()) {
        return QSize(140, 32); // Micro模式的最小尺寸
    }

    // 最小尺寸：单列布局，Micro模式
    QSize microItemSize = m_engine ? m_engine->calculateItemSize(DisplayMode::Micro) : QSize(140, 32);
    int rows = m_items.size();

    int width = microItemSize.width();
    int height = rows * microItemSize.height() + qMax(0, rows - 1) * DesignConstants::SPACING_MICRO;

    width += m_margins.left() + m_margins.right();
    height += m_margins.top() + m_margins.bottom();

    return QSize(width, height);
}

int AdaptiveFileLayout::heightForWidth(int width) const
{
    if (m_items.isEmpty()) {
        return minimumSize().height();
    }

    // 根据给定宽度计算所需高度
    int containerWidth = width - m_margins.left() - m_margins.right();
    int columns = calculateOptimalColumns(containerWidth);
    int rows = (m_items.size() + columns - 1) / columns;

    QSize itemSize = m_engine ? m_engine->calculateItemSize(m_currentDisplayMode) : QSize(280, 48);
    int spacing = getAdaptiveSpacing(m_currentDisplayMode);

    int height = rows * itemSize.height() + qMax(0, rows - 1) * spacing;
    height += m_margins.top() + m_margins.bottom();

    return height;
}

void AdaptiveFileLayout::setGeometry(const QRect& rect)
{
    QLayout::setGeometry(rect);

    if (m_lastGeometry != rect) {
        m_lastGeometry = rect;
        throttleLayoutUpdate();
    }
}

// === 响应式布局特性 ===

void AdaptiveFileLayout::setResponsiveEngine(ResponsiveFileListEngine* engine)
{
    if (m_engine != engine) {
        if (m_engine) {
            disconnect(m_engine, nullptr, this, nullptr);
        }

        m_engine = engine;

        if (m_engine) {
            connect(m_engine, &ResponsiveFileListEngine::displayModeChanged,
                    this, &AdaptiveFileLayout::onDisplayModeChanged);
            connect(m_engine, &ResponsiveFileListEngine::layoutUpdateRequired,
                    this, &AdaptiveFileLayout::updateLayout);

        }

        invalidateLayout();
    }
}

// === 布局控制 ===

void AdaptiveFileLayout::setColumns(int columns)
{
    if (m_columns != columns && columns > 0) {
        m_columns = columns;
        m_cache.invalidate();
        invalidateLayout();

    }
}

void AdaptiveFileLayout::setSpacing(int spacing)
{
    if (m_spacing != spacing && spacing >= 0) {
        m_spacing = spacing;
        m_cache.invalidate();
        invalidateLayout();

    }
}

void AdaptiveFileLayout::setMargins(int left, int top, int right, int bottom)
{
    QMargins newMargins(left, top, right, bottom);
    if (m_margins != newMargins) {
        m_margins = newMargins;
        setContentsMargins(m_margins);
        m_cache.invalidate();
        invalidateLayout();

    }
}

// === 动画控制 ===

void AdaptiveFileLayout::setAnimationEnabled(bool enabled)
{
    if (m_animationEnabled != enabled) {
        m_animationEnabled = enabled;

        if (!enabled) {
            stopAllAnimations();
        }

    }
}

void AdaptiveFileLayout::setAnimationDuration(int duration)
{
    if (m_animationDuration != duration && duration >= 0) {
        m_animationDuration = duration;
    }
}

// === 性能优化 ===

void AdaptiveFileLayout::enablePerformanceMode(bool enabled)
{
    if (m_performanceMode != enabled) {
        m_performanceMode = enabled;

        if (enabled) {
            setAnimationEnabled(false);
        }

    }
}

void AdaptiveFileLayout::setUpdateThrottleInterval(int msec)
{
    if (m_throttleInterval != msec && msec >= 0) {
        m_throttleInterval = msec;
        m_updateTimer->setInterval(msec);

    }
}

// === 布局信息查询 ===

int AdaptiveFileLayout::calculateOptimalColumns(int containerWidth) const
{
    if (!m_engine || containerWidth <= 0) {
        return 1;
    }

    return m_engine->calculateOptimalColumns(containerWidth);
}

QSize AdaptiveFileLayout::calculateItemSize(DisplayMode mode) const
{
    if (m_engine) {
        return m_engine->calculateItemSize(mode);
    }

    // 后备计算
    switch (mode) {
        case DisplayMode::Micro:    return QSize(140, 32);
        case DisplayMode::Compact:  return QSize(200, 40);
        case DisplayMode::Standard: return QSize(280, 48);
        case DisplayMode::Expanded: return QSize(380, 56);
        case DisplayMode::Full:     return QSize(480, 64);
    }
    return QSize(280, 48);
}

int AdaptiveFileLayout::calculateRowCount() const
{
    if (m_items.isEmpty() || m_columns <= 0) {
        return 0;
    }

    return (m_items.size() + m_columns - 1) / m_columns;
}

QRect AdaptiveFileLayout::getItemGeometry(int index) const
{
    if (index < 0 || index >= m_items.size()) {
        return QRect();
    }

    return m_items.at(index).currentGeometry;
}

// === 调试和诊断 ===

QString AdaptiveFileLayout::getLayoutDebugInfo() const
{
    return QString("AdaptiveFileLayout Debug:\n"
                   "  Items: %1\n"
                   "  Columns: %2\n"
                   "  Spacing: %3\n"
                   "  DisplayMode: %4\n"
                   "  Animation: %5\n"
                   "  Performance Mode: %6\n"
                   "  Is Updating: %7")
            .arg(m_items.size())
            .arg(m_columns)
            .arg(m_spacing)
            .arg(static_cast<int>(m_currentDisplayMode))
            .arg(m_animationEnabled ? "Enabled" : "Disabled")
            .arg(m_performanceMode ? "Enabled" : "Disabled")
            .arg(m_isUpdating ? "Yes" : "No");
}

void AdaptiveFileLayout::dumpLayoutStructure() const
{

    for (int i = 0; i < m_items.size(); ++i) {
        const auto& info = m_items.at(i);
                    .arg(i)
                    .arg(info.currentGeometry.x()).arg(info.currentGeometry.y())
                    .arg(info.currentGeometry.width()).arg(info.currentGeometry.height())
                    .arg(info.targetGeometry.x()).arg(info.targetGeometry.y())
                    .arg(info.targetGeometry.width()).arg(info.targetGeometry.height())
                    .arg(info.isAnimating ? "是" : "否");
    }
}

// === 便利方法（兼容现有代码） ===

void AdaptiveFileLayout::addWidget(QWidget* widget)
{
    if (widget) {
        addChildWidget(widget);
        addItem(new QWidgetItem(widget));
    }
}

// === 核心槽函数 ===

void AdaptiveFileLayout::onDisplayModeChanged(DisplayMode newMode, DisplayMode oldMode)
{
    if (m_currentDisplayMode != newMode) {

        m_currentDisplayMode = newMode;
        adjustSpacingForMode(newMode);

        // 重新计算列数
        if (m_engine) {
            int containerWidth = m_lastGeometry.width() - m_margins.left() - m_margins.right();
            int newColumns = m_engine->calculateOptimalColumns(containerWidth);
            setColumns(newColumns);
        }

        m_cache.invalidate();
        updateLayout();
    }
}

void AdaptiveFileLayout::onContainerResized()
{
    m_cache.invalidate();
    throttleLayoutUpdate();
}

void AdaptiveFileLayout::updateLayout()
{
    if (!m_lastGeometry.isValid()) {
        return;
    }

    calculateLayout(m_lastGeometry);
}

void AdaptiveFileLayout::invalidateLayout()
{
    m_layoutInvalid = true;
    m_cache.invalidate();

    if (m_updateTimer && !m_updateTimer->isActive()) {
        m_updateTimer->start();
    }
}

void AdaptiveFileLayout::onAnimationFinished()
{
    m_activeAnimations = qMax(0, m_activeAnimations - 1);

    if (m_activeAnimations == 0) {
        emit layoutUpdateFinished();
    }
}

void AdaptiveFileLayout::onThrottledUpdate()
{
    if (m_layoutInvalid && !m_isUpdating) {
        m_isUpdating = true;
        emit layoutUpdateStarted();

        calculateLayout(m_lastGeometry);

        m_layoutInvalid = false;
        m_isUpdating = false;

        if (m_activeAnimations == 0) {
            emit layoutUpdateFinished();
        }
    }
}

// === 核心布局计算 ===

void AdaptiveFileLayout::calculateLayout(const QRect& rect)
{
    if (m_items.isEmpty() || !rect.isValid()) {
        return;
    }

    // 检查缓存
    if (shouldUseCache(rect)) {

        for (int i = 0; i < m_items.size() && i < m_cache.cachedGeometries.size(); ++i) {
            m_items[i].currentGeometry = m_cache.cachedGeometries[i];
            m_items[i].targetGeometry = m_cache.cachedGeometries[i];

            if (m_items[i].item) {
                m_items[i].item->setGeometry(m_items[i].currentGeometry);
            }
        }
        return;
    }


    QList<QRect> newGeometries;
    calculateGridLayout(rect, newGeometries);

    // 更新缓存
    updateCache(rect, newGeometries);

    // 应用布局（带动画或直接应用）
    if (m_animationEnabled && !m_performanceMode) {
        animateToNewLayout(newGeometries);
    } else {
        // 直接应用布局
        for (int i = 0; i < m_items.size() && i < newGeometries.size(); ++i) {
            m_items[i].currentGeometry = newGeometries[i];
            m_items[i].targetGeometry = newGeometries[i];

            if (m_items[i].item) {
                m_items[i].item->setGeometry(newGeometries[i]);
            }
        }
    }
}

void AdaptiveFileLayout::calculateGridLayout(const QRect& rect, QList<QRect>& geometries)
{
    geometries.clear();

    QRect effectiveRect = rect.adjusted(m_margins.left(), m_margins.top(),
                                       -m_margins.right(), -m_margins.bottom());

    if (effectiveRect.width() <= 0 || effectiveRect.height() <= 0) {
        return;
    }

    // 获取当前显示模式的项目尺寸
    QSize itemSize = calculateItemSize(m_currentDisplayMode);
    int spacing = getAdaptiveSpacing(m_currentDisplayMode);

    // 重新计算最优列数
    int newColumns = calculateOptimalColumns(effectiveRect.width());
    if (newColumns != m_columns) {
        m_columns = newColumns;
    }

    // 计算实际项目宽度（平均分配）
    int actualItemWidth = (effectiveRect.width() - (m_columns - 1) * spacing) / m_columns;
    actualItemWidth = qMax(actualItemWidth, itemSize.width());

    // 生成所有项目的几何信息
    for (int i = 0; i < m_items.size(); ++i) {
        int row = i / m_columns;
        int col = i % m_columns;

        int x = effectiveRect.x() + col * (actualItemWidth + spacing);
        int y = effectiveRect.y() + row * (itemSize.height() + spacing);

        QRect itemGeometry(x, y, actualItemWidth, itemSize.height());
        geometries.append(itemGeometry);
    }

}

void AdaptiveFileLayout::adjustSpacingForMode(DisplayMode mode)
{
    int newSpacing = getAdaptiveSpacing(mode);
    if (newSpacing != m_spacing) {
        m_spacing = newSpacing;
    }
}

// === 动画系统 ===

void AdaptiveFileLayout::animateToNewLayout(const QList<QRect>& newGeometries)
{
    stopAllAnimations();

    m_activeAnimations = 0;

    for (int i = 0; i < m_items.size() && i < newGeometries.size(); ++i) {
        auto& info = m_items[i];
        const QRect& targetGeometry = newGeometries[i];

        if (info.currentGeometry != targetGeometry) {
            info.targetGeometry = targetGeometry;
            createItemAnimation(info, targetGeometry);
            m_activeAnimations++;
        }
    }

    if (m_activeAnimations > 0) {
        m_animationGroup->start();
    }
}

void AdaptiveFileLayout::createItemAnimation(LayoutItemInfo& info, const QRect& targetGeometry)
{
    if (!info.item || !info.item->widget()) {
        return;
    }

    if (info.animation) {
        info.animation->stop();
        info.animation->deleteLater();
    }

    info.animation = new QPropertyAnimation(info.item->widget(), "geometry", this);
    info.animation->setStartValue(info.currentGeometry);
    info.animation->setEndValue(targetGeometry);
    info.animation->setDuration(m_animationDuration);
    info.animation->setEasingCurve(QEasingCurve::OutCubic);

    connect(info.animation, &QPropertyAnimation::finished, this, [this, &info]() {
        info.currentGeometry = info.targetGeometry;
        info.isAnimating = false;
        onAnimationFinished();
    });

    connect(info.animation, &QPropertyAnimation::valueChanged, this, [this, &info](const QVariant& value) {
        info.currentGeometry = value.toRect();
    });

    info.isAnimating = true;
    m_animationGroup->addAnimation(info.animation);
}

void AdaptiveFileLayout::stopAllAnimations()
{
    if (m_animationGroup) {
        m_animationGroup->stop();
        m_animationGroup->clear();
    }

    for (auto& info : m_items) {
        if (info.animation) {
            info.animation->stop();
            info.animation->deleteLater();
            info.animation = nullptr;
        }
        info.isAnimating = false;
    }

    m_activeAnimations = 0;
}

// === 优化机制 ===

bool AdaptiveFileLayout::shouldUseCache(const QRect& rect) const
{
    return m_cache.isValid &&
           m_cache.lastContainerSize == rect.size() &&
           m_cache.lastDisplayMode == m_currentDisplayMode &&
           m_cache.lastColumns == m_columns &&
           m_cache.cachedGeometries.size() == m_items.size();
}

void AdaptiveFileLayout::updateCache(const QRect& rect, const QList<QRect>& geometries)
{
    m_cache.lastContainerSize = rect.size();
    m_cache.lastDisplayMode = m_currentDisplayMode;
    m_cache.lastColumns = m_columns;
    m_cache.cachedGeometries = geometries;
    m_cache.isValid = true;
}

void AdaptiveFileLayout::throttleLayoutUpdate()
{
    if (m_updateTimer && !m_updateTimer->isActive()) {
        m_updateTimer->start();
    }
}

// === 工具方法 ===

int AdaptiveFileLayout::getAdaptiveSpacing(DisplayMode mode) const
{
    switch (mode) {
        case DisplayMode::Micro:    return DesignConstants::SPACING_MICRO;
        case DisplayMode::Compact:  return DesignConstants::SPACING_SMALL;
        case DisplayMode::Standard: return DesignConstants::SPACING_NORMAL;
        case DisplayMode::Expanded: return DesignConstants::SPACING_LARGE;
        case DisplayMode::Full:     return DesignConstants::SPACING_LARGE;
    }
    return DesignConstants::SPACING_NORMAL;
}

QMargins AdaptiveFileLayout::getAdaptiveMargins(DisplayMode mode) const
{
    int margin = getAdaptiveSpacing(mode);
    return QMargins(margin, margin, margin, margin);
}

void AdaptiveFileLayout::ensureValidItemCount()
{
    // 清理无效的项目信息
    for (int i = m_items.size() - 1; i >= 0; --i) {
        if (!m_items[i].item) {
            m_items.removeAt(i);
        }
    }
}